// delete require.cache[require.resolve('./api')];
const http = require("http");
const axios = require("axios");
const cheerio = require("cheerio"); // 类似jquery

const server = http.createServer((req, response) => {
  response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
  switch (req.url) {
    case "/getdu":
      let status = Math.random() < 0.5;
      let url = status ? "https://lab.lalkk.com/fun/du/" : "https://8zt.cc/";
      let document = status
        ? ".main-wrapper .container #text"
        : ".main-wrapper .container #sentence";
      axios.get(url).then(res => {
        const $ = cheerio.load(res.data);
        const content = $(document)
          .text()
          .trim();
        let result = {
          ok: true,
          // status: status,
          // url: url,
          // document: document,
          data: content,
          msg: "请求成功"
        };
        response.write(JSON.stringify(result));
        response.end();
      });
      break;
    default:
      response.write(
        JSON.stringify({
          ok: false,
          data: "",
          msg: "请求错误"
        })
      );
      response.end();
      break;
  }
});

server.listen(3000, () => {
  console.log("服务已开启,监听3000端口");
});
